using System;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private static GameManager _instance;
    public static GameManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindAnyObjectByType<GameManager>();
            }
            return _instance;
        }
    }

    [Header("掉落物预制体引用")] [SerializeField] private GameObject itemPrefab;
    private readonly bool[] _clearance = new bool[7];
    private bool _hasShowedAfterword;
    private bool _hasShowedPrefaceword;
    private bool _hasSaving;
    private void Start()
    {
        QualitySettings.vSyncCount = 1;
        Application.targetFrameRate = 120;
    }

    public void Clearance(int levelIndex)
    {
        InventoryManager.Instance.RemoveItem(Constants.LEVEL_ITEM_REQUIREMENT[levelIndex]);
        _clearance[levelIndex] = true;
        if (IsAllClearance() && !_hasShowedAfterword)
        {
            GameOver();
        }
        else
        {
            UIManager.Instance.ShowClearancePanel();
        }
    }
    public bool IsAllClearance()
    {
        return _clearance[1] 
            && _clearance[2]
            && _clearance[3]
            && _clearance[4]
            && _clearance[5]
            && _clearance[6];
    }

    public bool GetClearance(int levelIndex)
    {
        return _clearance[levelIndex];
    }

    public void ClearProgress()
    {
        for (int i = 0; i < _clearance.Length; i++)
        {
            _clearance[i] = false;
        }
        _hasShowedAfterword = false;
        _hasShowedPrefaceword = false;
        _hasSaving = true;
        InventoryManager.Instance.ClearAll();
        MapManager.Instance.SetLastSceneIndex(-1);
    }

    public void StartOldGame()
    {
        if (_hasSaving)
        {
            if(InventoryManager.Instance.GetCurSlotCount() < 2) InventoryManager.Instance.SetBasicItems();
            UIManager.Instance.SwitchToPanel(1);
            UIManager.Instance.ShowScenePanel();
        }
        else
        {
            Debug.Log("无旧存档");
        }
    }

    public void SpawnItem(Vector3 position, int itemID)
    {
        GameObject spawnedItem = Instantiate(itemPrefab, position, Quaternion.identity);
        spawnedItem.GetComponent<Item>().SetItemID(itemID);
    }

    private void GameOver()
    {
        _hasShowedAfterword = true;
        UIManager.Instance.ShowAfterwordPanel();
    }

    public bool GetHasShowedPrefacePanel()
    {
        return _hasShowedPrefaceword;
    }

    public void SetHasShowedPrefacePanel(bool value)
    {
        _hasShowedPrefaceword = value;
    }
}
